Python 3: Most efficient way to create a [func(i) for i in range(N)] list comprehension

Posted by mejiwa on Stack Overflow See other posts from Stack Overflow or by mejiwa
Published on 2010-03-13T20:54:43Z Indexed on 2010/03/13 21:15 UTC
Read the original article Hit count: 214

Filed under:
|

Say I have a function func(i) that creates an object for an integer i, and N is some nonnegative integer. Then what's the fastest way to create a list (not a range) equal to this list

mylist = [func(i) for i in range(N)]

without resorting to advanced methods like creating a function in C? My main concern with the above list comprehension is that I'm not sure if python knows beforehand the length of range(N) to preallocate mylist, and therefore has to incrementally reallocate the list. Is that the case or is python clever enough to allocate mylist to length N first and then compute it's elements? If not, what's the best way to create mylist? Maybe this?

mylist = [None]*N
for i in range(N): mylist[i] = func(i)

© Stack Overflow or respective owner

Related posts about python

Related posts about list-comprehension